package com.xzjt.common.filter;

/**
 * @ClassName: JwtFilter
 * @Author: yuandong
 * @Date 2021/11/8 13:42
 */

import com.auth0.jwt.exceptions.JWTDecodeException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xzjt.common.components.JwtToken;
import com.xzjt.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 1、拦截用户请求 判断请求是否携带token 以及token 是否有效
 * 2、如果携带token 则交予shiro 后续处理
 * 3、未携带token 视为未登录下访问
 *
 * isAccessAllowed方法返回True，则不会再调用onAccessDenied方法，如果isAccessAllowed方法返回Flase,则会继续调用onAccessDenied方法
 *
 *
 *@Override isAccessAllowed() 时, 该方法是 在认证之前执行
 *  如果已经认证的用户, 直接放行(即 subject.isAuthenticated() 为 true)
 */
@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {

    private static String LOGIN_SIGN = "token";


    private final ObjectMapper objectMapper = new ObjectMapper();


    /**
     * 除了ShiroConfig中定义了放行的路径外, 其余路径皆会访问到这个方
     * 法, 因为 subject.isAuthenticated() 总是false
     * 拦截校验
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {

        // 完成token登入
        // 1. 检查请求头中是否含有token
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader(LOGIN_SIGN);
        // 2. 如果客户端没有携带token，拦下请求
        if (null == token || "".equals(token)) {
            this.responseTokenError(response, "请求头异常或token为空值!");
            return false;
        }
        // 3. 如果有，对token验证
        JwtToken jwtToken = new JwtToken(token);
        try {
            SecurityUtils.getSubject().login(jwtToken);
        } catch (AuthenticationException e) {
            responseTokenError(response, e.getMessage());
            return false;
        } catch (JWTDecodeException e) {
            responseTokenError(response, e.getCause().getMessage());
            return false;
        }
        // 放行 访问controller
        return true;
    }


    /**
     * 无需转发，直接返回Response信息 Token认证错误
     */
    private void responseTokenError(ServletResponse response, String msg) {
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setStatus(HttpStatus.OK.value());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        try {
            PrintWriter out = httpServletResponse.getWriter();
            // 序列化响应信息
            String data = this.objectMapper.writeValueAsString( R.tokenExpired());
            out.append(data);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }

    }



    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个OPTIONS请求，这里我们给OPTIONS请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(org.springframework.http.HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }


}
